import { ThemedText } from '@/components/ThemedText';
import { ThemedView } from '@/components/ThemedView';
import { useLocalSearchParams } from 'expo-router';
import React, { useState, useEffect } from 'react';
import { StyleSheet, View, Text, ScrollView, Image, TouchableOpacity } from 'react-native';
import Carousel from './brand';
import CustomModal from './CustomModal'; // 引入自定义模态框组件
import { vipShop } from '@/mock/Carousel';
import { Checkbox } from 'react-native-paper';

export default function Info() {
    const { item } = useLocalSearchParams<{ item: string }>();
    const parsedItem = JSON.parse(decodeURIComponent(item));
    const images = parsedItem.images;
    const [gift, setGift] = useState([]);
    const [quantity, setQuantity] = useState(1);
    const [total, setTotal] = useState(0);
    const [checkedItems, setCheckedItems] = useState({});

    useEffect(() => {
        setGift(vipShop.data);
        setTotal(parsedItem.sale);
    }, []);

    // 状态管理收藏按钮的图片路径
    const [isCollected, setIsCollected] = useState(false);
    // 状态管理模态框的显示
    const [isModalVisible, setModalVisible] = useState(false);

    const add = () => {
        setQuantity(quantity + 1);
        setTotal(total + parsedItem.price);
    };

    const diff = () => {
        if (quantity <= 1) {
            setQuantity(1);
            return false;
        }
        setQuantity(quantity - 1);
        setTotal(total - parsedItem.price);
    };

    const toggleCheck = (id) => {
        setCheckedItems(prevState => {
            const newCheckedItems = { ...prevState };
            newCheckedItems[id] = !newCheckedItems[id];
            return newCheckedItems;
        });
    };

    useEffect(() => {
        const newTotal = parsedItem.sale + Object.keys(checkedItems).reduce((acc, id) => {
            const item = gift.find(g => g.id === parseInt(id));
            return item ? acc + item.sale : acc;
        }, 0);
        setTotal(newTotal);
    }, [checkedItems, gift, parsedItem.sale]);

    return (
        <ThemedView>
            <ScrollView>
                <View style={{ flex: 1 }}>
                    <Carousel data={images}></Carousel>
                    <ThemedView style={{ padding: 10 }}>
                        <ThemedText style={{ fontSize: 20, color: 'black', marginBottom: 10, fontWeight: 600 }}>{parsedItem.title}</ThemedText>
                        <ThemedText style={{ fontSize: 13, color: 'grey', marginBottom: 10 }}>{parsedItem.desc}</ThemedText>
                        <ThemedView style={{ width: 150, flexDirection: 'row', justifyContent: 'space-between' }}>
                            <ThemedText style={{ fontSize: 14, color: 'red', marginBottom: 10 }}>￥{parsedItem.price}【会员价】</ThemedText>
                            <ThemedText style={{ fontSize: 14, color: 'gray', textDecorationLine: 'line-through', marginBottom: 10 }}>￥{parsedItem.sale}</ThemedText>
                        </ThemedView>
                        <ThemedText style={{ fontSize: 14, color: 'black', marginBottom: 10 }}>
                            <ThemedText style={{ color: 'gray' }}>配送：</ThemedText>
                            <ThemedText style={{ marginLeft: 10, color: 'black' }}>包邮（除青海、新疆、西藏等偏远地区外）</ThemedText>
                        </ThemedText>
                        <ThemedText style={{ fontSize: 14, color: 'black', marginBottom: 10 }}>
                            <ThemedText style={{ color: 'gray' }}>分类：</ThemedText>
                            <ThemedText style={{ marginLeft: 10, color: 'black' }}>{parsedItem.cate}</ThemedText>
                        </ThemedText>
                        <ThemedText style={{ fontSize: 14, color: 'black', marginBottom: 10 }}>
                            <ThemedText style={{ color: 'gray' }}>品牌：</ThemedText>
                            <ThemedText style={{ marginLeft: 20, color: 'black' }}>{parsedItem.brand}</ThemedText>
                        </ThemedText>
                        <ThemedText style={{ fontSize: 14, color: 'black', marginBottom: 10 }}>
                            <ThemedText style={{ color: 'gray' }}>阶段：</ThemedText>
                            <ThemedText style={{ marginLeft: 20, color: 'black' }}>{parsedItem.cate2}</ThemedText>
                        </ThemedText>
                        <ThemedText style={{ fontSize: 14, color: 'black', marginBottom: 10 }}>
                            <ThemedText style={{ color: 'gray' }}>毛重：</ThemedText>
                            <ThemedText style={{ marginLeft: 20, color: 'black' }}>{parsedItem.weight}g</ThemedText>
                        </ThemedText>
                        <ThemedText style={{ fontSize: 14, color: 'black', marginBottom: 10 }}>
                            <ThemedText style={{ color: 'gray' }}>保质:</ThemedText>
                            <ThemedText style={{ marginLeft: 20, color: 'black' }}>{parsedItem.Shelf}</ThemedText>个月以上</ThemedText>
                        <ThemedText style={{ fontSize: 14, color: 'black', marginBottom: 10 }}>
                            <ThemedText style={{ color: 'gray' }}>过期时间：</ThemedText>
                            <ThemedText style={{ marginLeft: 20, color: 'black' }}>{parsedItem.data}</ThemedText>
                        </ThemedText>
                        {
                            parsedItem.descImages.map((item, index) => {
                                return (
                                    <Image key={index} source={{ uri: item.src }} style={{ width: '100%', height: 200 }} />
                                )
                            })
                        }
                    </ThemedView>
                </View>
            </ScrollView>
            {/* 写一个底部的固定定位的盒子，内容包含私聊，收藏， 按钮有立即购买 */}
            <View style={styles.bottomBar}>
                <View style={styles.leftButtons}>
                    <TouchableOpacity style={styles.iconTextContainer} onPress={() => { /* 私聊逻辑 */ }}>
                        <Image source={require('../shopping/static/私聊.png')} style={styles.icon} />
                        <ThemedText style={styles.buttonLabel}>私聊</ThemedText>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.iconTextContainer} onPress={() => setIsCollected(!isCollected)}>
                        <Image source={isCollected ? require('../shopping/static/收藏1.png') : require('../shopping/static/收藏0.png')} style={styles.icon} />
                        <ThemedText style={styles.buttonLabel}>{isCollected ? '已收藏' : '收藏'}</ThemedText>
                    </TouchableOpacity>
                </View>
                <TouchableOpacity style={[styles.button, styles.buyButton]} onPress={() => setModalVisible(true)}>
                    <Text style={styles.buyButtonText}>立即购买</Text>
                </TouchableOpacity>
            </View>
            {/* 自定义模态框 */}
            <CustomModal 
                isVisible={isModalVisible} 
                onClose={() => setModalVisible(false)} 
                parsedItem={parsedItem} 
                gift={gift} 
                total={total}
            >
                <View style={styles.modalHeader}>
                    <Image source={{ uri: parsedItem.src }} style={styles.modalImage} />
                    <ThemedView style={{ marginLeft: 10, height: 90, flexDirection: 'column' }}>
                        <Text style={[styles.modalTitle, { flex: 1, textAlign: 'left' }]}>{parsedItem.title}</Text>
                        <Text style={[styles.modalPrice, { flex: 1, textAlign: 'left' }]}>￥{parsedItem.sale}</Text>
                        <Text style={[styles.modalPrice, { flex: 1, textAlign: 'left' }]}>总价：￥{total}</Text>
                    </ThemedView>
                    <View style={{ position: 'absolute', right: 20, top: 50 }}>
                        {/* 一个加减器，中间数字默认为1 */}
                        <View style={styles.quantityContainer}>
                            <TouchableOpacity style={styles.quantityButton} onPress={() => diff()}>
                                <Text style={styles.quantityText}>-</Text>
                            </TouchableOpacity>
                            <Text style={styles.quantityText}>{quantity}</Text>
                            <TouchableOpacity style={styles.quantityButton} onPress={() => add()}>
                                <Text style={styles.quantityText}>+</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
                <Text style={{ textAlign: 'left', fontWeight: 600, }}>换购会员福利</Text>
                {gift.map((item, index) => (
                    <View key={index} style={styles.giftItem}>
                        <Checkbox
                            status={checkedItems[item.id] ? 'checked' : 'unchecked'}
                            onPress={() => toggleCheck(item.id)}
                        />
                        <Image source={{ uri: item.src }} style={styles.giftImage} />
                        <View style={styles.giftDetails}>
                            <Text style={styles.giftTitle}>{item.title}</Text>
                            <Text style={styles.giftPrice}>￥{item.sale}</Text>
                        </View>
                    </View>
                ))}
            </CustomModal>
        </ThemedView>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        // 其他样式
    },
    quantityContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        marginTop: 10,
        width: 100,
        height: 40,
        borderRadius: 5,
        backgroundColor: '#f0f0f0',
        position: 'relative',
        top: '20%'
    },
    quantityButton: {
        width: 30,
        height: 30,
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 5,
    },
    quantityText: {
        fontSize: 16,
        color: '#333',
        marginHorizontal: 5,
    },
    bottomBar: {
        position: 'absolute',
        bottom: 0,
        left: 0,
        right: 0,
        backgroundColor: '#fff',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        padding: 10,
        borderTopWidth: 1,
        borderTopColor: '#ccc',
        elevation: 10, // 为了解决Android上的阴影问题
    },
    leftButtons: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    iconTextContainer: {
        flexDirection: 'column',
        alignItems: 'center',
        marginRight: 10, // 可以根据需要调整间距
        marginLeft: 10,
    },
    icon: {
        width: 20,
        height: 20,
        resizeMode: 'cover',
    },
    buttonLabel: {
        color: '#333',
        marginTop: 5, // 可以根据需要调整间距
        fontSize: 12,
    },
    button: {
        padding: 10,
        backgroundColor: '#f0f0f0',
        borderRadius: 5,
    },
    buyButton: {
        width: '30%',
        backgroundColor: '#ff4d4f',
        textAlign: 'center',
    },
    buyButtonText: {
        color: '#fff',
        textAlign: 'center',
    },
    modalHeader: {
        flexDirection: 'row',
        alignItems: 'center',
        position: 'relative',
        marginBottom: 10,
    },
    modalImage: {
        width: 80,
        height: 10,
        aspectRatio: 0.8,
        resizeMode: 'cover',
        marginTop: 10,
    },
    modalTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        marginBottom: 10,
    },
    modalPrice: {
        fontSize: 14,
        marginBottom: 10,
    },
    modalText: {
        fontSize: 14,
        marginBottom: 10,
    },
    giftItem: {
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: 10,
        padding: 10,
        borderBottomWidth: 1,
        borderBottomColor: '#ccc',
    },
    giftImage: {
        width: 50,
        height: 50,
        resizeMode: 'cover',
        marginRight: 10,
    },
    giftDetails: {
        flexDirection: 'column',
        flex: 1,
    },
    giftTitle: {
        fontSize: 14,
        fontWeight: 'bold',
    },
    giftPrice: {
        fontSize: 14,
        color: 'gray',
    },
});